<template>
  <GoBack content="角色信息" backUrl="/rolelist" />
  <div id="rolesave" class="content">
    <el-form
      ref="formRef"
      :rules="formRule"
      :model="form"
      label-width="100px"
      class="form-input-m"
      :inline-message="true"
    >
      <el-form-item prop="roleName" label="角色名称">
        <el-input v-model="form.roleName" type="text" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item prop="code" label="编码">
        <el-input v-model="form.code" type="text" placeholder="请输入编码"></el-input>
      </el-form-item>
      <el-form-item prop="remark" label="备注">
        <el-input v-model="form.remark" type="text" placeholder="请输入备注"></el-input>
      </el-form-item>
      <el-form-item prop="menu" label="菜单">
        <el-tree
          ref="menuTree"
          node-key="id"
          :data="menuList"
          show-checkbox
          :check-strictly="true"
          v-loading="loading"
          :props="defaultProps"
        ></el-tree>
      </el-form-item>
      <el-form-item prop="pms" label="权限">
        <el-tree
          ref="pmsTree"
          node-key="id"
          :data="pmsList"
          show-checkbox
          v-loading="loadingP"
          :props="defaultPropsPms"
        ></el-tree>
      </el-form-item>
      <el-form-item prop="sys" label="首页模块列数">
        <el-input-number v-model="form.homeColumn" :min="1" label="请输入列数"></el-input-number>
      </el-form-item>
      <el-form-item prop="sys" label="首页模块列表">
        <el-button type="success" @click="addHomeModule">新建模块</el-button>
      </el-form-item>
      <el-form-item prop="sys">
        <el-table row-key="id" :data="form.homeModuleList" :row-class-name="tableRowClassName">
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="模块名称" align="left" width="230">
            <template #default="scope">
              <el-input
                v-model="scope.row.name"
                type="text"
                placeholder="请输入模块名称"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="标题图标" align="left" width="230">
            <template #default="scope">
              <el-input
                v-model="scope.row.icon"
                type="text"
                placeholder="请输入标题图标"
                :prefix-icon="scope.row.icon"
                readonly
                ><template #append
                  ><el-button icon="Search" @click="showIconDialog(scope.row)" /></template
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="模块路径" align="left" width="230">
            <template #default="scope">
              <el-input v-model="scope.row.url" type="text" placeholder="请输入模块路径"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="模块高度(px)" align="left" width="180">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.height"
                :min="1"
                label="请输入模块高度"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="排序号" align="left" width="180">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.orderNo"
                :min="1"
                label="请输入排序号"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="90" align="center">
            <template #default="scope">
              <el-button
                size="small"
                icon="Delete"
                type="danger"
                plain
                circle
                @click="handleDeleteHomeModule(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loadingS" @click="saveRole(formRef)">保存</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      title="选择图标"
      v-model="showDialog"
      :close-on-click-modal="false"
      draggable
      width="600px"
    >
      <template v-for="ico in iconList" :key="ico">
        <el-icon size="20" class="icon" @click="selectIcon(ico)">
          <component :is="ico"></component>
        </el-icon>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import GoBack from '../../components/GoBack.vue';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import type { ElTree, FormInstance } from 'element-plus';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import { notifyType, notifyMessage } from '../../utils/common';
let { proxy }: any = getCurrentInstance();
let loading = ref(false);
let loadingS = ref(false);
let loadingP = ref(false);
let showDialog = ref(false);
let curRowIndex = ref(0);
let menuTree: any = ref<InstanceType<typeof ElTree>>();
let pmsTree: any = ref<InstanceType<typeof ElTree>>();
let formRef = ref<FormInstance>();
let form: any = reactive({
  id: '',
  code: '',
  roleName: '',
  homeColumn: 1,
  remark: '',
  homeModuleList: []
});
// 声明树形菜单为空的数组
let menuList: any = [];
// 声明权限列表数组
let pmsList: any = [];
let iconList: any = reactive([]);

// 配置默认选项，子级菜单为children,菜单名称为title 为了和后台数据库的名称统一起来
const defaultProps = {
  children: 'children',
  label: 'title'
};
const defaultPropsPms = {
  children: 'Permissions',
  label: 'name'
};

const formRule = {
  roleName: [
    {
      required: true,
      message: '请输入角色名称',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入角色编码',
      trigger: 'blur'
    }
  ]
};

onMounted(() => {
  for (const [key] of Object.entries(ElementPlusIconsVue)) {
    iconList.push(key);
  }

  getMenuList();
  getPmsList();
  if (proxy.$router.currentRoute.value.query.id) {
    form.id = proxy.$router.currentRoute.value.query.id;
    findRoleInfo();
  }
});

function tableRowClassName({ row, rowIndex }: any) {
  row.index = rowIndex;
}

// 获取菜单列
function getMenuList() {
  loading.value = true;
  const url = '/api/sys/menuList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      loading.value = false;
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        menuList = res.data.menuList;
      }
    })
    .catch((err: string) => {
      loading.value = false;
      notifyMessage(err, notifyType.warning, proxy);
    });
}
//获取权限列表
function getPmsList() {
  loadingP.value = true;
  const url = '/api/sys/findClassPermissionList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      loadingP.value = false;
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        pmsList = res.data.pmsList;
      }
    })
    .catch((err: string) => {
      loadingP.value = false;
      notifyMessage(err, notifyType.warning, proxy);
    });
}

// 获取角色信息
function findRoleInfo() {
  const url = '/api/sys/findRoleInfo';
  proxy.$http
    .get(url, { params: { id: form.id } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        if (res.data.role) {
          form.roleName = res.data.role.roleName;
          form.code = res.data.role.code;
          form.homeColumn = res.data.role.homeColumn;
          form.remark = res.data.role.remark;
          if (res.data.role.menus) {
            menuTree.value!.setCheckedKeys(res.data.role.menus);
          }
          if (res.data.role.permissions) {
            pmsTree.value!.setCheckedKeys(res.data.role.permissions);
          }
          if (res.data.role.homeModules) {
            form.homeModuleList.push(...res.data.role.homeModules);
          }
        }
      }
    })
    .catch((err: string) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}

function addHomeModule() {
  form.homeModuleList.push({
    idx: form.homeModuleList.length,
    id: '',
    name: '',
    icon: '',
    url: '',
    height: '',
    orderNo: form.homeModuleList.length + 1
  });
}

function showIconDialog(row: any) {
  curRowIndex.value = row.index;
  showDialog.value = true;
}

function selectIcon(ico: any) {
  showDialog.value = false;
  form.homeModuleList[curRowIndex.value].icon = ico;
}

function handleDeleteHomeModule(row: any) {
  if (row.id) {
    const idx = form.homeModuleList.findIndex((p: any) => p.id === row.id);
    if (idx) {
      form.homeModuleList.splice(idx, 1);
    }
  } else if (row.idx >= 0) {
    form.homeModuleList.splice(row.idx, 1);
  }
}

// 保存
function saveRole(formEl: any) {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (!valid) {
      return false;
    }

    loadingS.value = true;
    const postData = {
      id: form.id,
      code: form.code,
      roleName: form.roleName,
      homeColumn: form.homeColumn,
      remark: form.remark,
      menus: menuTree.value.getCheckedKeys(),
      permissions: pmsTree.value.getCheckedKeys(true),
      homeModules: form.homeModuleList
    };
    let url = '';
    if (form.id) {
      url = '/api/sys/editRole';
    } else {
      url = 'api/sys/addRole';
    }
    proxy.$http
      .post(url, postData)
      .then((res: any) => {
        loadingS.value = false;
        if (res.status.code === 1) {
          notifyMessage('保存成功', notifyType.success, proxy);
          form.id = res.data.roleId;
        } else {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        }
      })
      .catch((err: string) => {
        loadingS.value = false;
        notifyMessage(err, notifyType.warning, proxy);
      });
    return true;
  });
}
</script>
<style lang="scss">
#rolesave {
  .el-tree {
    width: 200px;
  }
  .icon {
    margin: 5px;
    cursor: pointer;
  }
}
</style>

